package com.example.user_module.login;

import androidx.room.Room;
import androidx.room.RoomDatabase;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.base_application.BaseApplication;
import com.example.common.EvenBusAction;
import com.example.common.mvvm.BaseEntity;
import com.example.common.mvvm.viewmodel.BaseViewModel;
import com.example.user_module.dao.UserDataBase;
import com.example.user_module.dao.UserEntity;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewMoel extends BaseViewModel<LoginRepository> {
    @Override
    public void onResult(BaseEntity entity) {
        if (entity instanceof UserInfoEntity){
            if (entity.message.equals("成功")){
                UserInfoEntity userEntity= (UserInfoEntity) entity;
                UserInfoEntity.DataBean.UserInfo data = userEntity.data.data;
                LogUtils.e("message"+userEntity.data.data.userId);
                SPUtils.getInstance().put("userid",data.userId);
                UserDataBase db = Room.databaseBuilder(BaseApplication.getInstance(), UserDataBase.class, "user.db").build();
                UserEntity userEntity1 = new UserEntity();
                userEntity1.qqOpenId=data.qqOpenId;
                userEntity1.avatar=data.avatar;
                userEntity1.expires_time=data.expires_time;
                userEntity1.followCount=data.followCount;
                userEntity1.likeCount=data.likeCount;
                userEntity1.topCommentCount=data.topCommentCount;
                userEntity1.name=data.name;
                save(userEntity1,db);
            }
        }
        if (entity instanceof UserEntity){
            if (entity.message.equals("保存成功")){
                EvenBusAction evenBusAction=new EvenBusAction();
                evenBusAction.action="refresh";
                EventBus.getDefault().post(evenBusAction);
            }
        }
    }
    public void save(UserEntity userEntity, UserDataBase db){
        repository.saveUser(userEntity,db)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }
    public void insertUser(String avatar,long expires_time ,
                           long followCount, long likeCount,
                           String name ,String qqOpenId ,
                           long topCommentCount){
        repository.requestInsertUser(avatar,expires_time,followCount,likeCount,name,qqOpenId,topCommentCount)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);

    }
    @Override
    protected void initData() {

    }
}
